package com.sunky.rfidapp.V2

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.rfid.rxobserver.RXObserver
import com.rfid.rxobserver.bean.RXInventoryTag
import com.sunky.db.model.EquipInfoV2
import com.sunky.db.util.DBManager
import com.sunky.db.util.getAll
import com.sunky.rfidapp.BaseActivity
import com.sunky.rfidapp.R
import com.sunky.rfidapp.util.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_equip_list.*
import kotlinx.android.synthetic.main.layout_title.*

class QueryInfoActivityV2 : BaseActivity() {
    data class ListData(var id: Long, var type: String, var typeName: String? = null,var serial:String?=null,var unitName:String?=null)

    lateinit var inflater: LayoutInflater
    var data: MutableList<ListData> = mutableListOf()
    //    var equipList: List<EquipInfo>? = null
//    var chipperList: List<ChiperEquipInfo>? = null
    var equipList: List<EquipInfoV2>? = null
    var epcSet = mutableSetOf<String>()//EPC 保存
    private val mInventoryObserver = object : RXObserver() {
        override fun onInventoryTag(tag: RXInventoryTag?) {
            Log.e("RXObserver", "onInventoryTag" + tag?.strEPC)
            Observable.just(tag?.strEPC)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        showInfoDialog("EPC:"+tag?.strEPC)
                    }
            tag?.strEPC?.apply {
                epcSet.add(this.replace(" ", ""))
            }
        }

        override fun onInventoryTagEnd(tagEnd: RXInventoryTag.RXInventoryTagEnd) {
            Log.e("RXObserver", "onInventoryTagEnd" + tagEnd.toString())
            Observable.just(epcSet)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {

                        combineListByRFID()
                        (List.adapter as QueryInfoActivityV2.QueryInfoAdapter).notifyDataSetChanged()
                        epcSet.clear()
                    }
        }

        override fun onExeCMDStatus(cmd: Byte, status: Byte) {
            Log.e("RXObserver", "onExeCMDStatus $cmd $status")
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_equip_list
    }

    override fun initView() {
        inflater = LayoutInflater.from(this)
        TvTitle.text = "信息查询"
        EtScan.hint = "请输入设备型号查询"
        var textListener = object : TextWatcher {
            override fun beforeTextChanged(var1: CharSequence, var2: Int, var3: Int, var4: Int) {}

            override fun onTextChanged(var1: CharSequence, var2: Int, var3: Int, var4: Int) {}

            override fun afterTextChanged(var1: Editable) {
                if (EtScan.text.isNotEmpty()) {
                    IvClear.visibility = View.VISIBLE
                } else {
                    IvClear.visibility = View.GONE
                }
            }
        }
        EtScan.addTextChangedListener(textListener)
        IvClear.setOnClickListener {
            EtScan.setText("")
        }
        IvQuery.setOnClickListener {
            doSearch()
        }
        List.setOnItemClickListener { adapterView, view, i, l ->
            if (data[i].typeName != null) {
                var intent = Intent(this@QueryInfoActivityV2, InfoDetailActivityV2::class.java)
                var find = equipList?.find {
                    it._id == data[i].id
                }
                CommonUtil.GlobalStorage["InfoDetailActivity"] = find ?: EquipInfoV2()
                startActivity(intent)
            }
        }
        List.adapter = QueryInfoAdapter()
    }

    override fun initData() {
        RFIDUtils.registerObserver(observer = mInventoryObserver)
        var equipObservable = Observable.create<List<EquipInfoV2>> {
            it.onNext(DBManager.getInstance().getAll(equipDaoV2)!!)
        }
        equipObservable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    equipList = it
                    combineList()
                    (List.adapter as QueryInfoAdapter).notifyDataSetChanged()
                }, {
                    toast("数据查询失败")
                    it.printStackTrace()
                    showException(it)
                })
    }
    override fun onDestroy() {
        super.onDestroy()
        RFIDUtils.unregisterObserver(mInventoryObserver)
    }

    private fun doSearch() {
        combineList()
        (List.adapter as QueryInfoActivityV2.QueryInfoAdapter).notifyDataSetChanged()
    }

    private fun combineList() {
        data.clear()
        if (EtScan.text.isEmpty()) {
            var curTitle = ""
            equipList?.sortedWith(Comparator { t1, t2 -> t1.equipType.compareTo(t2.equipType) })?.forEach {
                if (curTitle != it.equipTypeName) {
                    data.add(ListData(-1, it.equipTypeName))
                    curTitle = it.equipTypeName
                }
                data.add(ListData(it._id, it.equipTypeName, it.equipName,it.equipSerial,it.unitName))
            }
        } else {
            var curTitle = ""
            equipList?.filter {
                it.equipName.contains(EtScan.text.toString(), true)
            }?.sortedWith(Comparator { t1, t2 -> t1.equipType.compareTo(t2.equipType) })?.forEach {
                if (curTitle != it.equipTypeName) {
                    data.add(ListData(-1, it.equipTypeName))
                    curTitle = it.equipTypeName
                }
                data.add(ListData(it._id, it.equipTypeName, it.equipName,it.equipSerial,it.unitName))
            }
        }
    }

    private fun combineListByRFID() {
        EtScan.setText("")
        data.clear()
        if (epcSet.isNotEmpty()) {
            var curTitle = ""
            var list = equipList?.filter {
                epcSet.contains(it.codeinfo)
            }
            list?.isNotEmpty().yes {
                showInfoDialog("RFID查到信息")
            }
                    list?.sortedWith(Comparator { t1, t2 -> t1.equipType.compareTo(t2.equipType) })?.forEach {
                if (curTitle != it.equipTypeName) {
                    data.add(ListData(-1, it.equipTypeName))
                    curTitle = it.equipTypeName
                }
                data.add(ListData(it._id, it.equipTypeName, it.equipName,it.equipSerial,it.unitName))
            }
        }
    }

    inner class QueryInfoAdapter : BaseAdapter() {
        override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
            var view: View
            var type = getItemViewType(p0)
            var holder = if (p1 == null || (p1.tag as ViewHolderQueryInfo).type != type) {

                view = if (type == 0) {
                    inflater.inflate(R.layout.item_equip_info, p2, false)
                } else {
                    inflater.inflate(R.layout.item_equip_title, p2, false)
                }
                ViewHolderQueryInfo(view, type)
            } else {
                view = p1
                p1.tag as ViewHolderQueryInfo
            }
            var thisData = data[p0]
//            holder.TvName.text = thisData.typeName ?: thisData.type
            if (thisData.typeName == null) {
                holder.TvName?.text = thisData.type
            } else {
                holder.TvName?.text = thisData.typeName
            }
            if (type == 0){
                holder.tvSerial?.setTextValid(thisData.serial)
                holder.tvUnitName?.setTextValid(thisData.unitName)
            }
            return view
        }

        override fun getItem(p0: Int): Any {
            return data[p0]
        }

        override fun getItemId(p0: Int): Long {
            return p0.toLong()
        }

        override fun getCount(): Int {
            return data.size
        }

        override fun getItemViewType(position: Int): Int {
            return if (data[position].typeName != null) 0 else 1
        }

    }

    class ViewHolderQueryInfo {
        var TvName: TextView?
        var tvSerial: TextView?
        var tvUnitName: TextView?
        var type: Int

        constructor(view: View, type: Int) {
            this.type = type
            TvName = view.findViewById(R.id.TvName)
            tvSerial = view.findViewById(R.id.tvSerial)
            tvUnitName = view.findViewById(R.id.tvUnitName)
            view.tag = this
        }
    }
}